import Vue from 'vue';
import Router from 'vue-router';
import BaseLayout from '@/components/layouts/BaseLayout'
import Webview from '@/pages/Webview'

Vue.use(Router);

const router =  new Router({
  base: '/new/',
  routes: [
    {
      path: '/',
      component: BaseLayout,
      children: [
        {
          path: 'web',
          component: Webview,
          meta: {
            isWebView: true
          }
        }
      ],
    },
  ],
  // mode: 'history',
});

function createPackageRoutes (packageName, routes) {
  return [
    {
      path: '/' + packageName,
      component: BaseLayout,
      meta: {
        isSubPackage: true
      },
      children: [
        ...routes
      ],
    }
  ]
}

const isSetupSubPackage = []
console.log('process.env.packageDevPortMap', process.env.NODE_ENV_packageDevPortMap)
router.beforeEach((to, from, next) => {
  console.log('beforeEach', to, from)
  if (!to.matched.length) {
    const subPackageName = to.path.split('/', 2)[1]
    const subPackageUrl = `/subContent/platform/${subPackageName}/app.js`
    console.log('subPackageUrl', subPackageUrl)
    
    const script = document.getElementsByTagName("script")[0];
    const app = document.createElement("script");
    app.setAttribute('is-sub-package', 1)
    app.src = subPackageUrl;
    app.onload = () => {
      const routes = createPackageRoutes(subPackageName, window.subPackageRoutes[subPackageName])
      router.addRoutes(routes)
      next(to.fullPath)
      script.parentNode.removeChild(app)
    }
    script.parentNode.insertBefore(app, script);

  } else {
    next()
  }
})

export default router